
package com.ctrip.corp.obt.shard.sql.mybatis.proxy;

import lombok.Getter;
import org.apache.ibatis.binding.MapperProxyFactory;
import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author marco.zheng
 * @version 1.0
 * @date 2022/01/14
 * override {@link MapperProxyFactory}
 * use {@link OverrideMapperMethod}
 */
public class OverrideMapperProxyFactory<T> {
    
    @Getter
    private final Class<T> mapperInterface;
    @Getter
    private final Map<Method, OverrideMapperProxy.MapperMethodInvoker> methodCache = new ConcurrentHashMap<>();
    
    public OverrideMapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    @SuppressWarnings("unchecked")
    protected T newInstance(OverrideMapperProxy<T> mapperProxy) {
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
    }

    public T newInstance(SqlSession sqlSession) {
        final OverrideMapperProxy<T> mapperProxy = new OverrideMapperProxy<>(sqlSession, mapperInterface, methodCache);
        return newInstance(mapperProxy);
    }
}
